<template>
<div>
    My Token:
    {{token}}
    <div>
        <input v-model="address" type="text" placeholder="请输入地址" style="width:400px">
        <input v-model="num" type="number" placeholder="请输入数量">
        <button @click="send">Send</button>
        <button @click="query">Query</button>
        {{result}}
    </div>
</div>
</template>

<script>
import Web3 from 'web3'
import contract from 'truffle-contract'
import artifacts from '../../build/contracts/FirstToken.json'
const FirstTokenContract = contract(artifacts)

export default {
   name: 'FirstToken',
    data() {
        return {
            web3: null,
            account: null,
            token: null,
            address: '0x554f40f004758c2043992379465a04371ffdd9e1',
            num: 10,
            result: null
        }
    },
    created() {
        if (typeof web3 !== 'undefined') {
            this.web3 = Object.freeze(new Web3(web3.currentProvider))
        } else {
            this.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"))
        }
        FirstTokenContract.setProvider(this.web3.currentProvider)
        this.account = this.web3.eth.coinbase
        this.web3.eth.defaultAccount = this.web3.eth.coinbase
        FirstTokenContract.defaults({from: this.web3.eth.coinbase})
        FirstTokenContract.deployed().then((instance) => {
            instance.balanceOf(this.account).then((value) => this.token = value)
        });
    },
    methods: {
        send() {
            return FirstTokenContract.deployed()
                .then((instance) => {
                    console.log('from:' + this.account)
                    console.log('to:' + this.address);
                    instance.transfer(this.address, this.num)
                    return instance
                })
                .then((instance) => {
                    instance.balanceOf(this.address).then((value) => this.result = value)
                    instance.balanceOf(this.account).then((value) => this.token = value)
                })
                .catch((e) => {
                    console.error(e)
                })
        },
        query() {
            return FirstTokenContract.deployed()
                .then((instance) => {
                    instance.balanceOf(this.address).then((value) => this.result = value)
                })
                .catch((e) => {
                    console.error(e)
                })
        },
    }
}
</script>
